<?php
class SaveOption extends Action {
	/*
	 * (non-PHPdoc) @see Action::execute()
	 */
	public function execute($params) {
		check_login ( ADMIN_LOGIN_PAGE );
		$rst = array ('success' => false );
		$opts = rqst ( 'opt' );
		
		if (empty ( $opts )) {
			$rst ['msg'] = '未有要保存的选项';
		} else {
			$group = rqst ( 'group', 'base' );
			$opts = apply_filter ( 'on_save_option_' . $group, $opts );
			if (is_array ( $opts ) && ! empty ( $opts )) {
				$cpM = new CoreOptionModel ();
				$cpM->begin ();
				$ecnt = array ();
				foreach ( $opts as $group => $option ) {
					foreach ( $option as $key => $value ) {
						if (strlen ( trim ( $value ) ) > 0) {
							$opt = array ();
							$opt ['option_group'] = $group;
							$opt ['option_value'] = $value;
							$where ['option_name'] = $key;
							if ($cpM->exist ( $where )) {
								$result = $cpM->update ( $opt, $where );
							} else {
								$opt ['option_name'] = $key;
								$result = $cpM->insert ( $opt );
							}
							if (! $result) {
								$ecnt [] = $key;
							}
						}
					}
				}
				$cpM->commit ();
				$rst ['success'] = true;
				$rst ['ecnt'] = $ecnt;
			} else if ($opts === true) {
				$rst ['success'] = true;
			} else {
				$rst ['msg'] = $opts;
			}
		}
		return new JsonView ( $rst );
	}
}